package com.nandi.deviceinstall.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.ArrayAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.view.TimePickerView
import com.nandi.deviceinstall.R
import com.nandi.deviceinstall.base.BaseMvpActivity
import com.nandi.deviceinstall.bean.*
import com.nandi.deviceinstall.common.Constant
import com.nandi.deviceinstall.contract.TapRecordContract
import com.nandi.deviceinstall.presenter.TapRecordPresenter
import com.nandi.deviceinstall.ui.adapter.TapRecordAdapter
import com.nandi.deviceinstall.util.CustomToast
import com.nandi.deviceinstall.util.SharedTool
import com.nandi.deviceinstall.weight.InitDataListener
import kotlinx.android.synthetic.main.activity_tap_record.*
import kotlinx.android.synthetic.main.toolbar_back_include.*
import java.text.SimpleDateFormat
import java.util.*

class TapRecordActivity : BaseMvpActivity<TapRecordPresenter>(), TapRecordContract.View {

    private var current = 1
    private var pageSize = 10
    private var listCitys: MutableList<CityBean.DataBean> = mutableListOf()
    private var listTowns: MutableList<TownBean.DataBean> = mutableListOf()
    private var listMonitorNums: MutableList<ListMonitorNumBean.DataBean> = mutableListOf()
    private lateinit var mAdapter: TapRecordAdapter
    private lateinit var cityAdapter: ArrayAdapter<String>
    private lateinit var townAdapter: ArrayAdapter<String>
    private lateinit var disasterNameAdapter: ArrayAdapter<String>
    private lateinit var disasterNuAdapter: ArrayAdapter<String>
    private lateinit var monitorNumAdapter: ArrayAdapter<String>
    private var startDate = Calendar.getInstance()
    //private var endDate = Calendar.getInstance()
    private lateinit var timePicker: TimePickerView
    private var isStartTime = false
    private var sort = 2
    private var isSearch = false
    private var token = ""
    private var isAddress = false
    private var citys = mutableListOf<String>()
    private var towns = mutableListOf<String>()
    private var disastersName = mutableListOf<String>()
    private var disastersNu = mutableListOf<String>()
    private var monitorNums = mutableListOf<String>()
    private var isSelectCity = false
    private var isSelectTown = false


    override val layoutId: Int
        get() = R.layout.activity_tap_record

    @SuppressLint("SimpleDateFormat")
    override fun initView() {
        mPresenter = TapRecordPresenter()
        mPresenter.attachView(this)
        tv_title_toolbar.text = "踩点记录"
        title_image.visibility =View.GONE
        token = SharedTool.get(context, Constant.TOKEN, "") as String

        //startDate.set(2000, 0, 1, 0, 0, 0)

        val allShow = booleanArrayOf(true, true, true, true, true, true)

        timePicker = TimePickerBuilder(context, OnTimeSelectListener { date, _ ->
            if (isStartTime) {
                startTime.text = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date)
            } else {
                endTime.text = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date)
            }
        })
                .setType(allShow)
                .setCancelText("取消")
                .setSubmitText("确认")
                .setContentTextSize(18)
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择日期")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setDate(startDate)
                //.setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")
                .isDialog(false)
                .build()

        data_show.layoutManager = LinearLayoutManager(context)
        mAdapter = TapRecordAdapter(R.layout.item_record)
        data_show.adapter = mAdapter
        mAdapter.setEnableLoadMore(true)
        mAdapter.setOnLoadMoreListener({
            if (isSearch) {
                var city = ""
                if (district.getmPosition() != -1) {
                    city = listCitys[district.getmPosition()].areaCode!!
                }
                var town = ""
                if (township.getmPosition() != -1) {
                    town = listTowns[township.getmPosition()].areaCode!!
                }
                loadMore(city, sort, town,
                        disasterName.text.toString(), disasterNum.text.toString(), monitorNum.text.toString(),
                        startTime.text.toString(), endTime.text.toString(), 1)
            } else {
                loadMore("", sort, "", "", "", "", "", "", 1)
            }
        }, data_show)

        mAdapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(context, TapRecordInfoActivity::class.java)
            intent.putExtra("id", mAdapter.getItem(position)?.id)
            startActivity(intent)
        }

        mAdapter.setOnItemChildClickListener { _, _, position ->
            MaterialDialog.Builder(this)
                    .title("提示")
                    .content("确认删除?")
                    .positiveText("确认")
                    .negativeText("取消")
                    .onPositive { _, _ ->
                        mPresenter.requestDeleteTapRecord(token, mAdapter.getItem(position)!!.id)
                    }
                    .show()
        }

        srlTemplate.setOnRefreshListener {
            refresh()
        }

        refresh()
        initListener()
    }

    private fun initListener() {
        iv_back_toolbar.setOnClickListener { finish() }

        address.setOnClickListener {
            isAddress = true
            mPresenter.requestListCity(token, "")
        }

        time.setOnClickListener {
            if (sort == 1) {
                sort = 2
            } else if (sort == 2) {
                sort = 1
            }
            current = 1
            if (isSearch) {
                var city = ""
                if (district.getmPosition() != -1) {
                    city = listCitys[district.getmPosition()].areaCode!!
                }
                var town = ""
                if (township.getmPosition() != -1) {
                    town = listTowns[township.getmPosition()].areaCode!!
                }
                getData(city, sort, town,
                        disasterName.text.toString(), disasterNum.text.toString(), monitorNum.text.toString(),
                        startTime.text.toString(), endTime.text.toString(), 1)
            } else {
                getData("", sort, "", "", "", "", "", "", 1)
            }
        }
        //策划菜单
        more.setOnClickListener {
            if (!drawer.isDrawerOpen(root)) {
                drawer.openDrawer(root)
            }
        }
        cancel.setOnClickListener {
            if (drawer.isDrawerOpen(root)) {
                drawer.closeDrawer(root)
                isSearch = false
            }
        }

        submit.setOnClickListener {
            isSearch = true
            current = 1
            var city = ""
            if (district.getmPosition() != -1) {
                city = listCitys[district.getmPosition()].areaCode!!
            }
            var town = ""
            if (township.getmPosition() != -1) {
                town = listTowns[township.getmPosition()].areaCode!!
            }
            getData(city, sort, town,
                    disasterName.text.toString(), disasterNum.text.toString(), monitorNum.text.toString(),
                    startTime.text.toString(), endTime.text.toString(), 1)
        }

        district.setInitDataListener {
            mPresenter.requestListCity(token, "")
        }
        district.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (district.isTextChanged) {
                    isSelectCity = true
                    township.text = ""
                    disasterName.setText("")
                    disasterNum.text = ""
                    monitorNum.text = ""
                    isSelectCity = false
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        township.setInitDataListener {
            if (district.text.isNotEmpty()) {
                val id = listCitys[district.getmPosition()].id
                mPresenter.requestListTown(token, id)
            } else {
                showLongToast("请先选择区县!")
            }
        }
        township.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (township.isTextChanged) {
                    isSelectTown = true
                    disasterName.setText("")
                    disasterNum.text = ""
                    monitorNum.text = ""
                    isSelectTown = false
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        disasterName.setInitDataListener {
            if (township.text.isNotEmpty()) {
                val areaCode = listTowns[township.getmPosition()].areaCode
                mPresenter.requestListDisaster(token, 1, 1000000, areaCode!!)
            } else {
                showLongToast("请先选择乡镇!")
            }
        }
        disasterName.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (disasterName.isTextChanged) {
                    disasterNum.text = ""
                    monitorNum.text = ""
                }

                if (!disasterName.isMySelected && !isSelectCity && !isSelectTown) {
                    if (district.text.isEmpty()) {
                        CustomToast.showToast(context, "请选择区县")
                        return
                    }
                    if (township.text.isEmpty()) {
                        CustomToast.showToast(context, "请选择乡镇")
                        return
                    }
                    if (p0.toString().isEmpty()) {
                        return
                    }
                    val areaCode = listTowns[township.getmPosition()].areaCode
                    mPresenter.requestDisName(token, p0.toString(), areaCode!!)
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

        })

        disasterNum.setInitDataListener {
            if (township.text.isNotEmpty()) {
                val areaCode = listTowns[township.getmPosition()].areaCode
                mPresenter.requestDisNum(token, disasterName.text.toString(), areaCode!!)
            } else {
                showLongToast("请先选择灾害点名称!")
            }
        }

        disasterNum.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (disasterNum.isTextChanged) {
                    monitorNum.text = ""
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
        })

        monitorNum.setInitDataListener {
            if (disasterNum.text.isNotEmpty()) {
                mPresenter.requestListMonitorNum(token, disasterNum.text.toString())
            } else {
                showLongToast("请选择灾害点编号!")
            }
        }

        startTime.setOnClickListener {
            isStartTime = true
            timePicker.show()
        }

        endTime.setOnClickListener {
            isStartTime = false
            timePicker.show()
        }
    }

    override fun handlerDeleteTap(result: DeleteBean) {
        if (result.data) {
            refresh()
        }
    }

    override fun handlerListDisasterResult(result: DisasterBean) {
        disastersName.clear()
        result.data?.forEach {
            disastersName.add(it.disasterName!!)
        }
        disasterNameAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, disastersName)
        disasterName.setAdapter(disasterNameAdapter)
        disasterName.showPopWindow()
    }

    override fun handlerDisNum(result: DisNumBean) {
        disastersNu.clear()
        result.data?.forEach {
            disastersNu.add(it)
        }
        disasterNuAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, disastersNu)
        disasterNum.setAdapter(disasterNuAdapter)
        disasterNum.showPopWindow()
    }

    override fun handlerListTownResult(result: TownBean) {
        listTowns.clear()
        listTowns.addAll(result.data!!)
        towns.clear()
        result.data?.forEach {
            towns.add(it.areaName!!)
        }
        townAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, towns)
        township.setAdapter(townAdapter)
        township.showPopWindow()
    }

    override fun handlerListCityResult(result: CityBean) {
        /*listCitys.clear()
        listCitys.addAll(result.data!!)
        var citys = mutableListOf<String>()
        result.data?.forEach {
            citys.add(it.areaName!!)
        }
        cityAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, citys)
        district.setAdapter(cityAdapter)
        district.showPopWindow()*/
        listCitys.clear()
        listCitys.addAll(result.data!!)
//        var citys = mutableListOf<String>()
        citys.clear()
        result.data?.forEach {
            citys.add(it.areaName!!)
        }
        if (isAddress) {
            citys.add(0, "全部")
            val pvOptions = OptionsPickerBuilder(this@TapRecordActivity
                    , OnOptionsSelectListener { options1, _, _, _ ->
                //返回的分别是三个级别的选中位置
                address.text = citys[options1]
                if (options1 == 0) {
                    getData("", sort, "", "", "", "",
                            "", "", 1)
                } else {
                    getData(listCitys[options1 - 1].areaCode!!, sort, "", "", "", "",
                            "", "", 1)
                }
            }).build<Any>()
            pvOptions.setPicker(citys as List<String>)
            pvOptions.show()
            isAddress = false
        } else {
            cityAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, citys)
            district.setAdapter(cityAdapter)
            district.showPopWindow()
        }
    }

    override fun handlerListRecordResult(result: TapRecordBean) {
        srlTemplate.isRefreshing = false
        mAdapter.data.clear()
        setData(result.data?.records!!)
        if (drawer.isDrawerOpen(root)) {
            drawer.closeDrawer(root)
        }
    }

    override fun handlerDisNameResult(result: DisNameBean) {
        if (result.data!!.records!!.isNotEmpty()) {
            disastersName.clear()
            result.data?.records?.forEach {
                disastersName.add(it.disasterName!!)
            }
            disasterNameAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, disastersName)
            disasterName.setAdapter(disasterNameAdapter)
            disasterName.showPopWindow()
        } /*else {
            showShortToast("没有相关灾害点!")
        }*/
    }

    private fun loadMore(areaCode: String, sort: Int, townCode: String, disasterName: String,
                         disNo: String, monitorNo: String, startTime: String, endTime: String, isAppAdd: Int) {
        current++
        getData(areaCode, sort, townCode, disasterName, disNo, monitorNo, startTime, endTime, isAppAdd)
    }

    private fun refresh() {
        current = 1
        isSearch = false
        getData("", 2, "", "", "", "", "", "", 1)
    }

    private fun getData(areaCode: String, sort: Int, townCode: String, disasterName: String,
                        disNo: String, monitorNo: String, startTime: String, endTime: String, isAppAdd: Int) {
        mPresenter.requestListRecord(token, current, pageSize,
                1, areaCode, sort, townCode, disasterName, disNo,
                monitorNo, startTime, endTime, isAppAdd)
    }

    private fun setData(data: MutableList<TapRecordBean.DataBean.RecordsBean>) {

        val size = data.size
        mAdapter.addData(data)
        if (size < pageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd()
        } else {
            mAdapter.loadMoreComplete()
        }
    }

    override fun showLoading() {
    }

    override fun hideLoading() {
    }

    override fun onError(msg: String, code: Int) {
        CustomToast.showToast(context, msg)
    }

    override fun handlerMonitorNum(result: ListMonitorNumBean) {

        if (result.data != null) {
            listMonitorNums.clear()
            listMonitorNums.addAll(result.data!!)
            //val monitorNums = mutableListOf<String>()
            monitorNums.clear()
            result.data?.forEach {
                monitorNums.add(it.monitorNo!!)
            }
            monitorNumAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, monitorNums)
            monitorNum.setAdapter(monitorNumAdapter)
            monitorNum.showPopWindow()
        } else {
            showLongToast("此灾害点没有监测点编号!")
        }
    }

}
